<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\api\logic;

use app\api\error\CodeBase;
use app\api\error\Common as CommonError;
use \Firebase\JWT\JWT;

/**
 * 接口基础逻辑
 */
class Common extends ApiBase
{
	/**
	 * 登录接口逻辑
	 */
	public function logins($data = [])
	{

		$validate_result = $this->validateUser->scene('login')->check($data);
		if (!$validate_result) {
			return CommonError::$usernameOrPasswordEmpty;
		}
		$member = db('user')->where(['username' => $data['username']])->find();
		// 若不存在用户则注册
		if (empty($member))
		{
			return CommonError::$passwordError;
		}else{
			if (data_md5_key($data['password'],$member['salt']) !== $member['password']) {
				return CommonError::$passwordError;
			}
		}
		if($member['status'] != 1){
			return CommonError::$usernameError;
		}
		return $this->tokenSign($member,1);
	}
	/**
	 * 登录接口逻辑
	 */
	public function wxLogin($data = [])
	{
		if (empty($data['openid'])) {
			$info=getUserInfo($data['jscode']);
			$data['unionid']=$info['unionid'];
			session('wxinfo', $info);
		}
		$member = db('user')->where(['unionid' => $data['unionid']])->find();
		// 若不存在用户则注册
		if (empty($member))
		{
			return $this->apiReturn();
		}else{
			if($member['status'] != 1){
				return CommonError::$usernameError;
			}
			return $this->tokenSign($member,1);
		}
	}
	/**
	 * 注册方法
	 */
	public function wxRegisterLogin($data)
	{
		if (empty($data['openid'])) {
			$info=session('wxinfo');
		}
		$phone=$data['phone'];
		if( $msg = checkCode($phone,$data['code'],5)){
			return $msg;
		}
		$member=db('user')->where(['username'=>$phone])->find();
		if(!empty($member)){
			$res=db('user')->where('id',$member['id'])->update(['openid'=>$info['openid'],'unionid'=>$info['unionid']]);
			if($res != false){
				return $this->tokenSign($member,1);
			}else{
				return CommonError::$registerError;
			}

		}else{
			if(!empty($data['invitation'])){
				$istj=db('user')->where(array('invitation'=>$data['invitation']))->value('id');
				if(empty($istj)){
					return CommonError::$userError;
				}
				$data['tjid']=$istj;

			}else{
				$data['tjid']=10019;
			}
			$data['openid'] = $info['openid'];
			$data['unionid'] = $info['unionid'];
			$nocode=db('user')->where("id=".$data['tjid'])->value("nocodea");
			$salt=rand(1000,9999);
			$data['username'] = $phone;
			$data['name'] = $info['nickname'];
			$data['headimg'] = $info['headimgurl'];
			$data['status'] = 1;
			$data['salt'] = $salt;
			$data['nocodea'] = $nocode.$data['tjid'].',';
			$data['create_time'] = time();
			$data['password']  = data_md5_key(substr($phone,-6),$salt);
			$data['passwords']  = data_md5_key(substr($phone,-6),$salt);
			$data['invitation']=initcode();
			unset($data['code']);
			$data['id']=db('user')->insertGetId($data);
			if($data['id'] != false){
				return $this->tokenSign($data,1);
			}else{
				return CommonError::$registerFail;
			}
		}
	}
	 /**
     * 充值列表
     */
    public function czList($data)
    {
        $where = [];     
        !empty($data['user_id']) && $where['user_id'] = $data['user_id']; 
		$list_rows=!empty($data['list_rows'])?$data['list_rows']:10;
		$data['page']=!empty($data['page'])?$data['page']:1;
		$page=($data['page']-1)*$list_rows;
		$list=db('cz')->where($where)->limit($page,$list_rows)->select();
        return $list;
    }
	/**
     * 充值
     */
	public function rechargeAdd($data){		
		$data['create_time']=time();
		$res=db('cz')->insert($data);
		if($res){
			return $this->apiReturn();	
		}else{
			return CommonError::$paramError;	
		}
		
	}
	/**
	 * 发送邮件
	 */
	Public function emailSend($data = []){
		$codes=rand(100000,999999);
		$txt = sprintf("UDC Code: %s", $codes);		
		$res=send_email($data['email'], 'UDC', $txt);	
		if($res){
			$is=db('email')->where(array('email'=>$data['email']))->value('count');			
			if(!empty($is)){
				$datas = array(
					'codes'=>$codes,
					'count'=>$is+1,
					'create_time'=>time()
				);
				db('email')->where(array('email'=>$data['email']))->update($datas);
			}else{
				$datas = ['codes' => $codes, 'email'=>$data['email'],'create_time' => time(),'count'=>1];
				db('email')->insert($datas);
			}
			
			return $this->apiReturn();
		}else{
			return $this->apiReturn(['code' => 1010008, API_MSG_NAME => '发送失败']);
		}
	}
	/**
	 * 手机验证码登录
	 */
	Public function checkInvitation($data){
		$id=db('user')->where('invitation',$data['invitation'])->value('id');
		if(empty($id)){
			return CommonError::$invitationError;
		}else{
			return $this->apiReturn();
		}
	}
    /**
     * 登录接口逻辑
     */
    public function login($data = [])
    {   
    	
		$validate_result = $this->validateUser->scene('login')->check($data);      
		if (!$validate_result) {           
			return CommonError::$usernameOrPasswordEmpty;
		}
		$member = db('user')->where(['username' => $data['username']])->find();
		// 若不存在用户则注册
		if (empty($member))
		{
			return CommonError::$passwordError;
		}else{
			if (data_md5_key($data['password'],$member['salt']) !== $member['password']) {            
				return CommonError::$passwordError;
			}
		}
		if($member['status'] != 1){
			return CommonError::$usernameError;
		}
		return $this->tokenSign($member);    	
    }
	/**
	 * 手机验证码登录
	 */
	Public function checkLogin($data){
		if(!empty($data['type'])){
			if( $msg = checkCode($data['phone'],$data['code'],0)){
				return $msg;
			}else{
				return $this->apiReturn();
			}
		}
		$is=db('user')->where(['username'=>$data['phone'],'is'=>$data['is']])->value('id');
		if(empty($is)){
			return CommonError::$usernameError;
		}
		if( $msg = checkCode($data['phone'],$data['code'],1)){
			return $msg;
		}else{
			$member = db('user')->where(['username' => $data['phone']])->find();
			return $this->tokenSign($member);
		}
	}
    /**
     * 发送短信
     */
	Public function send($data = []){
		
		$type=$data['type'];
		if($type == 0){
			$id=db('user')->where('username',$data['phone'])->value('id');
			if(!empty($id)){
				return CommonError::$registerError;
			}
		}
		if($type == 2 || $type == 1){
			$phone=db('user')->where(array('username'=>$data['phone']))->value('phone');
			if(empty($phone)){
				return CommonError::$userError;		
			}
		}else{
			$phone=$data['phone'];
		}	
		$code=rand(100000,999999);
        $arr=array('code'=>$code);
		//0,注册，1登录，2找回密码，3转让，4提现
		$marr=array(0=>'SMS_196835009',1=>'SMS_196835008',2=>'SMS_196835008',3=>'SMS_196657980',4=>'SMS_196652962',5=>'SMS_196835012');
		$response=$this->sendSms($phone,$marr[$type],$arr);			
        //$resarr=json_decode( json_encode($response),true);
		if(!$response){
			$is=db('code')->where("phone='".$phone."' and type=".$type)->value('count');
			if(!empty($is)){
				$data = array(
					'code'=>$code,
					'count'=>$is+1,
					'create_time'=>time()
				);
				db('code')->where(array('phone'=>$phone,'type'=>$type))->update($data);
			}else{
				$data = ['code' => $code, 'phone'=>$phone,'create_time' => time(),'type'=>$type,'count'=>1];
				db('code')->insert($data);
			}		
			return $this->apiReturn();			
		}else{	
			return ['code' => 1010008, API_MSG_NAME => $response];
			//return CommonError::$codeFail;	
		}
	}
	private function sendSms($phone,$model,$arr)
    {	
	    $parameter['sign_name']     = '五域联盟';
	    $parameter['template_code'] = $model;
	    $parameter['phone_number']  = $phone;
	    $parameter['template_param'] = $arr;	  
	    return $this->serviceSms->driverAlidy->sendSms($parameter);
    }
    /**
     * 注册方法
     */
    public function register($data)
    {  	
		$phone=$data['username'];
		if( $msg = checkCode($phone,$data['code'],0)){
			return $msg;
		}
		$is=db('user')->where('username',$phone)->value('id');
		if(!empty($is)){
			return CommonError::$registerError;	
		}
		if(!empty($data['invitation'])){
			$istj=db('user')->where(array('invitation'=>$data['invitation']))->value('id');
			if(empty($istj)){
				return CommonError::$userError;
			}
			$data['tjid']=$istj;

		}else{
			return CommonError::$invitationError;
		}
		unset($data['invitation']);
		db('user')->startTrans();
		$nocode=db('user')->where("id=".$data['tjid'])->value("nocodea");
		$salt=rand(1000,9999);
		$data['phone'] = $phone;
		$data['status'] = 1;
		$data['salt'] = $salt;
		$data['nocodea'] = $nocode.$data['tjid'].',';
		$data['create_time'] = time();		
        $data['password']  = data_md5_key($data['password'],$salt);
		$data['passwords']  = data_md5_key($data['password'],$salt);
		$data['invitation']=initcode();
		$ida=db('user')->insertGetId($data);		
		/*$num=db('user')->where('id',$data['tjid'])->value('num');
		$isnum = config('mdc_share');
		if($num > intval($isnum)-2){
			money_log($data['tjid'],1);
			$count=db('user')->where('id',$data['tjid'])->value('count');
			$re=db('user')->where('id',$data['tjid'])->update(array('num'=>0,'count'=>$count+1));
		}else{
			$re=db('user')->where('id',$data['tjid'])->update(array('num'=>$num+1));
		}
		if(!empty($data['sbh']) && !empty($istj)){
			$r=$this->getShare($data['sbh'],$ida,$data['tjid']);
		}else{
			$r=true;
		}*/
		if($ida != false){
			db('user')->commit();
			return $this->apiReturn();
		}else{
			db('user')->rollback();
			return CommonError::$registerFail;	
		}       	
    }

	/**
     * 分享收入
     */
	 private function getShare($sbh,$id,$tjid){
		$arr=parse_config_array('shareMoney');
		if($arr['is'] == 1){
			$is=db('user')->where('sbh',$sbh)->value('id');
			if(!empty($is) && $is != $id){
				return true;
			}else{
				$re = moneyyj_log($arr['my'],$id,6,$id);
				$res = moneyyj_log($arr['fxr'],$tjid,7,$id);
				if($re && $res){
					return true;
				}else{
					return false;
				}
			}
		}else{
			return true;
		}
	 }
    /**
     * 找回密码
     */
    public function getPassword($data)
    {  		
		$id=db('user')->where('username',$data['username'])->value('id');
		if(empty($id)){
			return CommonError::$userError;	
		}
		$salt=rand(1000,9999);
		$datas['salt']=$salt;
        $datas['password']  = data_md5_key($data['password'],$salt);

		if( $msg = checkCode($data['username'],$data['code'],2)){
			return $msg;
		}
		
		$res=db('user')->where('username',$data['username'])->update($datas);			
		if($res !== false){
			//import("hx.Easemob");
			//$hx=new \Easemob();
			//$username=db('user')->where('username',$data['username'])->value('id');
			//$hx->resetPassword($username,$datas['password']);
			return $this->apiReturn();
		}else{
			return CommonError::$registerFail;	
		}
        	
    }
    /**
     * JWT验签方法
     */
    public static function tokenSign($member,$is=0)
    {        
        $key = API_KEY . JWT_KEY;
		$member['headimg']=!empty($member['headimg'])?$member['headimg']:'/upload/headimg.png';
        //$jwt_data = ['user_id' => $member['id'], 'name' => $member['name'], 'username' => $member['username'],'headimg' => $member['headimg'],'phone' => $member['phone'],'resume_id' => $resume, 'create_time' => $member['create_time'], 'password' => $member['password']];
        $jwt_data = $member;
		$jwt_datas = ['user_id' => $member['id'],'username' => $member['username']];
        $token = [
            "iss"   => "LpTx JWT",         // 签发者
            "iat"   => TIME_NOW,              // 签发时间
            "exp"   => TIME_NOW + TIME_NOW,   // 过期时间
            "aud"   => 'LpTx',             // 接收方
            "sub"   => 'LpTx',             // 面向的用户
            "data"  => $jwt_datas
        ];
        $jwt = JWT::encode($token, $key);
		if(empty($is)){
			db('user')->where('id',$member['id'])->update(array('token'=>$jwt,'timeout'=>time()));
		}else{
			$jwt=db('user')->where('id',$member['id'])->value('token');
			if(empty($jwt)){
				db('user')->where('id',$member['id'])->update(array('token'=>$jwt,'timeout'=>time()));
			}
		}
        $jwt_data['user_token'] = $jwt;
        return $jwt_data;
    }
    
    /**
     * 修改密码
     */
    public function changePassword($data)
    {
        
        $member = get_member_by_token($data['user_token']);
        
        $member_info = $this->logicUser->getUserInfo(['id' => $member->user_id]);
        
        if (empty($data['old_password']) || empty($data['new_password'])) {
            
            return CommonError::$oldOrNewPassword;
        }
        
        if (data_md5_key($data['old_password']) !== $member_info['password']) {
            
            return CommonError::$passwordError;
        }

        $member_info['password'] = $data['new_password'];
        
        $result = $this->logicUser->setInfo($member_info);
        
        return $result ? CodeBase::$success : CommonError::$changePasswordFail;
    }
   
	/**
	 * 地区
	 */
	public function regionList()
	{
		if(!$data = $this->cacheData('_addresslist')){
			$list=db('region')->where('level',1)->select();
			foreach($list as $k=>$v){
				$citylist=db('region')->where(array('province_code'=>$v['code'],'level'=>2))->select();
				foreach($citylist as $key=>$val){
					$citylist[$key]['countyList']=db('region')->where(array('city_code'=>$val['code'],'level'=>3))->select();
				}
				$list[$k]['cityList']=$citylist;
			}
			$this->cacheData('_addresslist',$list);
		}else{
			$list=$data;
		}
		return $list;
	}
}
